package com.jianwei.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;


public class LoginFilter extends HttpServlet implements Filter {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6641567182960704316L;
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain arg2) throws IOException, ServletException {
			HttpServletRequest req = (HttpServletRequest)request;
			HttpServletResponse res = (HttpServletResponse)response;
			if(!StringUtils.isEmpty(req.getParameter("checkSession"))){
				arg2.doFilter(request, response);
			}else{
				String key = req.getParameter("user.user_name");
				if(req.getServletContext().getAttribute(key) != null){
					res.setContentType("text/json;charset=UTF-8");
					res.getWriter().write(JSONObject.fromObject("{\"error\":\"logged\"}").toString());
				}else{
					arg2.doFilter(request, response);
				}
			}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}
}
